﻿using BestHTTP.SocketIO;
using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SocketClient : MonoBehaviour
{
    public static SocketClient Instance;

    public event Action<string> OnReceivePCGameStatusEvent;

    public InputField IpInputField;

    private string _hostAddress = "192.168.2.176";
    //private string _hostAddress = "192.168.10.80";

    private  SocketManager _io;
    private  Socket _socket;

    private void Awake()
    {
        Instance = this;
        InitSocketManager();
    }

    private void Start()
    {
        //if (IPHandel.ReadIP() == "")
        //{
        //    IpInputField.gameObject.SetActive(true);
        //}
        //else
        //{
        //    _hostAddress = IPHandel.ReadIP();
        //    Debug.Log("保存本地的IP ：" + _hostAddress);
        //    IpInputField.gameObject.SetActive(false);
        //    InitSocketManager();
        //}
        //IpInputField.onEndEdit.AddListener(OnInputFieldEnd);
    }

    private void OnInputFieldEnd(string ip)
    {
        _hostAddress = ip;
        IpInputField.gameObject.SetActive(false);
        IPHandel.SaveIP(ip);
    }

    private void InitSocketManager()
    {
        _io = new SocketManager(new Uri(String.Format("http://{0}/socket.io/", _hostAddress+ ":9999")));
        _io.Open();
        _socket = _io.GetSocket();
        _socket.On(SocketIOEventTypes.Disconnect, OnDisConnectCallBack);
        _socket.On(SocketIOEventTypes.Error, OnErrorCallBack);
        _socket.On(SocketIOEventTypes.Connect, OnConnectCallBack);
        _socket.On("step", OnReceivePCGameDataMesg); // 监听 PC socket 事件
    }

    private void OnConnectCallBack(Socket socket, Packet packet, object[] args)
    {
        Debug.Log("Connected!");
        SendClientMsg("init");
    }

    private void OnDisConnectCallBack(Socket socket, Packet packet, object[] args)
    {
        Debug.Log("DisConnected!");
    }

    private void OnErrorCallBack(Socket socket, Packet packet, object[] args)
    {
        Error error = args[0] as Error;
        Debug.Log("Error111: " + error);

        switch (error.Code)
        {
            case SocketIOErrors.User:
                Debug.LogWarning("Exception in an event handler!");
                break;
            case SocketIOErrors.Internal:
                Debug.LogWarning("Internal error!");
                break;
            default:
                Debug.LogWarning("server error!");
                break;
        }
    }

    /// <summary>
    /// 监听 PC socket 事件回调
    /// </summary>
    /// <param name="socket"></param>
    /// <param name="packet"></param>
    /// <param name="args"></param>
    private void OnReceivePCGameDataMesg(Socket socket, Packet packet, object[] args)
    {
        //Debug.Log("OnReceiveOCRDataMesg");
        try
        {      
            JsonData jsonData = JsonMapper.ToObject(args[0].ToString());
            string socketType = jsonData["key"].ToString();
            if (socketType == "bailian_game")
            {
                string gameStatus = jsonData["data"]["msg"].ToString();
                if (OnReceivePCGameStatusEvent !=null)
                {
                    OnReceivePCGameStatusEvent.Invoke(gameStatus);
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);
            throw;
        }
    }

    public void SendClientMsg(string msg)
    {
        if (_socket == null) { Debug.Log("未初始化"); return; }
        JsonData msgJson = new JsonData();
        msgJson["key"] = "bailian_ipad";
        msgJson["data"] = new JsonData();
        msgJson["data"]["msg"] = msg;
        _socket.Emit("step", msgJson.ToJson());
    }

    public void SendRole1Msg(string role1Msg)
    {
        if (_socket == null) { Debug.Log("未初始化"); return; }
        JsonData msgJson = new JsonData();
        msgJson["key"] = "bailian_role1";
        msgJson["data"] = new JsonData();
        msgJson["data"]["msg"] = role1Msg;
        _socket.Emit("step", msgJson.ToJson());
    }

    public void SendRole2Msg(string role2Msg)
    {
        if (_socket == null) { Debug.Log("未初始化"); return; }
        JsonData msgJson = new JsonData();
        msgJson["key"] = "bailian_role2";
        msgJson["data"] = new JsonData();
        msgJson["data"]["msg"] = role2Msg;
        _socket.Emit("step", msgJson.ToJson());
    }

    public void SendRole3Msg(string role3Msg)
    {
        if (_socket == null) { Debug.Log("未初始化"); return; }
        JsonData msgJson = new JsonData();
        msgJson["key"] = "bailian_role3";
        msgJson["data"] = new JsonData();
        msgJson["data"]["msg"] = role3Msg;
        _socket.Emit("step", msgJson.ToJson());
    }

    public void SendVolume(string msg) {
        if (_socket == null) {
            Debug.Log("未初始化");
            return;
        }
        JsonData msgJson = new JsonData();
        msgJson["key"] = "Audio_volume";
        msgJson["data"] = new JsonData();
        msgJson["data"]["msg"] = msg;
        _socket.Emit("step", msgJson.ToJson());
    }

    private void OnDisable()
    {
        _io.Close();
    }
}
